package com.java2007.hotel.controller.backend;

import com.java2007.hotel.constant.ServletConstant;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author ghy
 * @version 1.0
 * @date 2021-01-22
 */
public class BaseServlet extends HttpServlet {

    /**
     * 无论什么请求，都会由service方法来处理
     */
    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        try {

            String methodStr = request.getParameter(ServletConstant.METHOD);

            /*if(StringUtils.isEmpty(methodStr)) {
                response.sendRedirect(request.getContextPath() + "/index.jsp");
                return;
            }*/

            //得到Class对象
            Class clazz = this.getClass();
            //得到Method对象
            Method method = clazz.getMethod(methodStr, HttpServletRequest.class, HttpServletResponse.class);

            //调用方法
            Object object = method.invoke(this, request, response);

            if(object != null) {
                if(object instanceof String) {
                    String result = (String) object;
                    String url = null;
                    //判断是否转发还是转定向，还是直接响应字符串
                    if(result.startsWith(ServletConstant.PRE_FORWARD)){
                        //转发: forward:
                        //   /backend/detail/foodtype/food-type-list.jsp
                        url = result.substring(result.indexOf(ServletConstant.TAG) + 1);
                        request.getRequestDispatcher(url).forward(request, response);
                    } else if(result.startsWith(ServletConstant.PRE_REDIRECT)){
                        //重定向: redirect:
                        url = result.substring(result.indexOf(ServletConstant.TAG) + 1);
                        response.sendRedirect(request.getContextPath() + url);
                    } else {
                        //其他: 直接响应字符串
                        response.getWriter().write(result);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write(ServletConstant.COMMON_ERROR_MESSAGE);
            //response.sendRedirect(request.getContextPath() + "/index.jsp");
        }
    }

}
